<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-top">
        <h2>健身目标</h2>
        <el-button 
          type="primary" 
          icon="Plus" 
          @click="createTestGoal"
          size="small"
          v-if="goals.length === 0">
          创建测试目标
        </el-button>
      </div>
      <p>设定和跟踪您的健身计划</p>
    </div>
    
    <el-card class="filter-card">
      <div class="filter-container">
        <div class="filter-item">
          <el-select 
            v-model="statusFilter" 
            placeholder="目标状态"
            clearable
            style="width: 150px;"
            @change="fetchGoals"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <el-select 
            v-model="typeFilter" 
            placeholder="目标类型"
            clearable
            style="width: 150px;"
            @change="fetchGoals"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <el-button type="success" @click="goToAddGoal">
            <el-icon><Plus /></el-icon>
            添加新目标
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="进行中" name="active">
        <el-empty v-if="activeGoals.length === 0" description="暂无进行中的目标" />
        <div v-else class="goals-container">
          <el-card 
            v-for="goal in activeGoals" 
            :key="goal.id" 
            class="goal-card"
            :class="{ 'warning': isExpired(goal) }"
          >
            <template #header>
              <div class="goal-header">
                <div class="title-container">
                  <el-tag :type="getGoalTypeTag(goal.type)" class="goal-type-tag">
                    {{ getGoalTypeDisplay(goal.type) }}
                  </el-tag>
                  <span class="goal-title">{{ goal.title }}</span>
                </div>
                <div class="goal-actions">
                  <el-button 
                    type="primary" 
                    circle 
                    size="small"
                    @click="editGoal(goal)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button 
                    type="danger" 
                    circle 
                    size="small"
                    @click="deleteGoal(goal)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            <div class="goal-content">
              <div class="goal-info">
                <div class="info-row">
                  <span class="label">目标值：</span>
                  <span class="value">{{ goal.targetValue }} {{ goal.unit }}</span>
                </div>
                <div class="info-row" v-if="goal.targetDate">
                  <span class="label">截止日期：</span>
                  <span class="value" :class="{ 'text-danger': isExpired(goal) }">
                    {{ formatDate(goal.targetDate) }}
                    <el-tag v-if="isExpired(goal)" type="danger" size="small">已逾期</el-tag>
                  </span>
                </div>
                <div class="info-row" v-if="goal.frequency && goal.frequencyUnit">
                  <span class="label">频率：</span>
                  <span class="value">{{ goal.frequency }}次{{ getFrequencyUnitDisplay(goal.frequencyUnit) }}</span>
                </div>
                <div class="info-row" v-if="goal.description">
                  <span class="label">描述：</span>
                  <span class="value">{{ goal.description }}</span>
                </div>
              </div>
              <div class="goal-progress">
                <div class="progress-header">
                  <span>完成进度</span>
                  <span>{{ goal.progress }}%</span>
                </div>
                <el-progress 
                  :percentage="goal.progress" 
                  :status="getProgressStatus(goal.progress)"
                />
                <div class="progress-actions">
                  <el-button type="primary" size="small" @click="showUpdateProgress(goal)">
                    更新进度
                  </el-button>
                  <el-button type="success" size="small" @click="markAsCompleted(goal)">
                    标记为已完成
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="已完成" name="completed">
        <el-empty v-if="completedGoals.length === 0" description="暂无已完成的目标" />
        <div v-else class="goals-container">
          <el-card 
            v-for="goal in completedGoals" 
            :key="goal.id" 
            class="goal-card completed-goal"
          >
            <template #header>
              <div class="goal-header">
                <div class="title-container">
                  <el-tag :type="getGoalTypeTag(goal.type)" class="goal-type-tag">
                    {{ getGoalTypeDisplay(goal.type) }}
                  </el-tag>
                  <span class="goal-title">{{ goal.title }}</span>
                </div>
                <div class="goal-actions">
                  <el-button 
                    type="danger" 
                    circle 
                    size="small"
                    @click="deleteGoal(goal)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            <div class="goal-content">
              <div class="goal-info">
                <div class="info-row">
                  <span class="label">目标值：</span>
                  <span class="value">{{ goal.targetValue }} {{ goal.unit }}</span>
                </div>
                <div class="info-row" v-if="goal.completedDate">
                  <span class="label">完成日期：</span>
                  <span class="value">{{ formatDate(goal.completedDate) }}</span>
                </div>
                <div class="info-row" v-if="goal.targetDate">
                  <span class="label">目标日期：</span>
                  <span class="value">{{ formatDate(goal.targetDate) }}</span>
                </div>
                <div class="info-row" v-if="goal.description">
                  <span class="label">描述：</span>
                  <span class="value">{{ goal.description }}</span>
                </div>
              </div>
              <div class="goal-progress">
                <div class="progress-header">
                  <span>完成进度</span>
                  <span>{{ goal.progress }}%</span>
                </div>
                <el-progress 
                  :percentage="goal.progress" 
                  status="success"
                />
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="未达成" name="failed">
        <el-empty v-if="failedGoals.length === 0" description="暂无未达成的目标" />
        <div v-else class="goals-container">
          <el-card 
            v-for="goal in failedGoals" 
            :key="goal.id" 
            class="goal-card failed-goal"
          >
            <template #header>
              <div class="goal-header">
                <div class="title-container">
                  <el-tag :type="getGoalTypeTag(goal.type)" class="goal-type-tag">
                    {{ getGoalTypeDisplay(goal.type) }}
                  </el-tag>
                  <span class="goal-title">{{ goal.title }}</span>
                </div>
                <div class="goal-actions">
                  <el-button 
                    type="danger" 
                    circle 
                    size="small"
                    @click="deleteGoal(goal)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            <div class="goal-content">
              <div class="goal-info">
                <div class="info-row">
                  <span class="label">目标值：</span>
                  <span class="value">{{ goal.targetValue }} {{ goal.unit }}</span>
                </div>
                <div class="info-row" v-if="goal.targetDate">
                  <span class="label">截止日期：</span>
                  <span class="value">{{ formatDate(goal.targetDate) }}</span>
                </div>
                <div class="info-row" v-if="goal.description">
                  <span class="label">描述：</span>
                  <span class="value">{{ goal.description }}</span>
                </div>
              </div>
              <div class="goal-progress">
                <div class="progress-header">
                  <span>完成进度</span>
                  <span>{{ goal.progress }}%</span>
                </div>
                <el-progress 
                  :percentage="goal.progress" 
                  status="exception"
                />
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 更新进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="更新目标进度"
      width="500px"
    >
      <div v-if="currentGoal" class="progress-dialog-content">
        <h3>{{ currentGoal.title }}</h3>
        <p>目标值: {{ currentGoal.targetValue }} {{ currentGoal.unit }}</p>
        <el-form :model="progressForm" label-width="120px">
          <el-form-item label="当前进度">
            <el-slider
              v-model="progressForm.progress"
              :min="0"
              :max="100"
              :step="1"
              show-input
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="progressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProgress" :loading="submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllFitnessGoals,
  getFitnessGoalsByStatus,
  getFitnessGoalsByType,
  updateGoalProgress,
  completeGoal,
  deleteFitnessGoal,
  createFitnessGoal
} from '@/api/fitnessGoal'

const router = useRouter()
const loading = ref(false)
const goals = ref([])
const statusFilter = ref('')
const typeFilter = ref('')
const activeTab = ref('active')
const progressDialogVisible = ref(false)
const currentGoal = ref(null)
const progressForm = ref({
  progress: 0
})
const submitting = ref(false)

// 状态选项
const statusOptions = [
  { value: 'ACTIVE', label: '进行中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'FAILED', label: '未达成' },
  { value: 'ABANDONED', label: '已放弃' }
]

// 类型选项
const typeOptions = [
  { value: 'WEIGHT_LOSS', label: '减重目标' },
  { value: 'EXERCISE_FREQUENCY', label: '运动频率' },
  { value: 'DISTANCE', label: '距离目标' },
  { value: 'STRENGTH', label: '力量目标' },
  { value: 'ENDURANCE', label: '耐力目标' },
  { value: 'CUSTOM', label: '自定义' }
]

// 过滤后的目标列表
const activeGoals = computed(() => {
  return goals.value.filter(goal => goal.status === 'ACTIVE')
})

const completedGoals = computed(() => {
  return goals.value.filter(goal => goal.status === 'COMPLETED')
})

const failedGoals = computed(() => {
  return goals.value.filter(goal => goal.status === 'FAILED' || goal.status === 'ABANDONED')
})

// 判断目标是否已逾期
const isExpired = (goal) => {
  if (!goal.targetDate || goal.status !== 'ACTIVE') return false
  const targetDate = new Date(goal.targetDate)
  return targetDate < new Date()
}

// 获取进度条状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success'
  if (progress >= 60) return 'success'
  if (progress >= 20) return ''
  return 'exception'
}

// 获取目标类型显示名称
const getGoalTypeDisplay = (type) => {
  const typeMap = {
    'WEIGHT_LOSS': '减重目标',
    'EXERCISE_FREQUENCY': '运动频率',
    'DISTANCE': '距离目标',
    'STRENGTH': '力量目标',
    'ENDURANCE': '耐力目标',
    'CUSTOM': '自定义'
  }
  return typeMap[type] || type
}

// 获取目标类型对应的标签类型
const getGoalTypeTag = (type) => {
  const tagMap = {
    'WEIGHT_LOSS': 'danger',
    'EXERCISE_FREQUENCY': 'primary',
    'DISTANCE': 'success',
    'STRENGTH': 'warning',
    'ENDURANCE': 'info',
    'CUSTOM': ''
  }
  return tagMap[type] || ''
}

// 获取频率单位显示名称
const getFrequencyUnitDisplay = (unit) => {
  const unitMap = {
    'DAY': '每天',
    'WEEK': '每周',
    'MONTH': '每月'
  }
  return unitMap[unit] || unit
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 切换标签页
const handleTabClick = (tab) => {
  activeTab.value = tab.props.name
}

// 获取目标列表
const fetchGoals = async () => {
  loading.value = true;
  
  try {
    let response = [];
    
    if (statusFilter.value && typeFilter.value) {
      // 暂时没有同时按状态和类型筛选的API，先获取按状态筛选的结果，再在前端过滤
      response = await getFitnessGoalsByStatus(statusFilter.value);
      response = response.filter(goal => goal.type === typeFilter.value);
    } else if (statusFilter.value) {
      response = await getFitnessGoalsByStatus(statusFilter.value);
    } else if (typeFilter.value) {
      response = await getFitnessGoalsByType(typeFilter.value);
    } else {
      // 尝试获取所有目标
      try {
        console.log('尝试获取所有健身目标');
        response = await getAllFitnessGoals();
        console.log('获取所有健身目标结果:', response.length);
        
        // 如果结果为空，尝试分别获取不同状态的目标
        if (!response || response.length === 0) {
          console.log('未获取到健身目标，尝试按状态获取');
          
          // 依次尝试获取各种状态的目标
          const statusList = ['ACTIVE', 'COMPLETED', 'FAILED', 'ABANDONED'];
          for (const status of statusList) {
            console.log(`尝试获取${status}状态的目标`);
            const statusGoals = await getFitnessGoalsByStatus(status);
            console.log(`${status}状态目标数量:`, statusGoals.length);
            response = [...response, ...statusGoals];
          }
          
          // 去重
          const idSet = new Set();
          response = response.filter(goal => {
            if (idSet.has(goal.id)) return false;
            idSet.add(goal.id);
            return true;
          });
          
          console.log('合并后的总目标数量:', response.length);
        }
      } catch (e) {
        console.error('获取所有目标失败，尝试按状态获取:', e);
        // 如果获取所有目标失败，尝试获取活跃状态的目标
        response = await getFitnessGoalsByStatus('ACTIVE');
      }
    }
    
    goals.value = response;
  } catch (error) {
    console.error('获取健身目标失败:', error);
    ElMessage.error('获取健身目标失败，请重试或联系管理员');
    goals.value = []; // 确保设置为空数组避免界面错误
  } finally {
    loading.value = false;
  }
}

// 编辑目标
const editGoal = (goal) => {
  router.push(`/fitness-goals/edit/${goal.id}`)
}

// 删除目标
const deleteGoal = (goal) => {
  ElMessageBox.confirm(
    '确定要删除此健身目标吗？删除后无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteFitnessGoal(goal.id)
      ElMessage.success('删除成功')
      fetchGoals()
    } catch (error) {
      console.error('删除健身目标失败:', error)
      ElMessage.error('删除健身目标失败')
    }
  }).catch(() => {})
}

// 显示更新进度对话框
const showUpdateProgress = (goal) => {
  currentGoal.value = goal
  progressForm.value.progress = goal.progress
  progressDialogVisible.value = true
}

// 提交进度更新
const submitProgress = async () => {
  if (!currentGoal.value) return
  
  submitting.value = true
  
  try {
    await updateGoalProgress(currentGoal.value.id, progressForm.value.progress)
    ElMessage.success('进度更新成功')
    fetchGoals()
    progressDialogVisible.value = false
  } catch (error) {
    console.error('更新进度失败:', error)
    ElMessage.error('更新进度失败')
  } finally {
    submitting.value = false
  }
}

// 标记为已完成
const markAsCompleted = async (goal) => {
  try {
    await completeGoal(goal.id)
    ElMessage.success('目标已标记为完成')
    fetchGoals()
  } catch (error) {
    console.error('完成目标失败:', error)
    ElMessage.error('完成目标失败')
  }
}

// 跳转到添加目标页面
const goToAddGoal = () => {
  router.push('/fitness-goals/add')
}

// 创建测试目标
const createTestGoal = async () => {
  try {
    loading.value = true;
    
    // 创建一个测试目标
    const testGoal = {
      title: '测试健身目标',
      type: 'EXERCISE_FREQUENCY',
      description: '这是一个用于测试API的自动创建目标',
      targetValue: '3',
      unit: '次',
      startDate: new Date().toISOString().substring(0, 19).replace('T', ' '),
      targetDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().substring(0, 19).replace('T', ' '),
      progress: 0,
      status: 'ACTIVE',
      frequency: 3,
      frequencyUnit: 'WEEK'
    };
    
    console.log('创建测试目标数据:', testGoal);
    const response = await createFitnessGoal(testGoal);
    console.log('测试目标创建结果:', response);
    
    ElMessage.success('测试目标创建成功');
    
    // 重新加载目标列表
    await fetchGoals();
  } catch (error) {
    console.error('创建测试目标失败:', error);
    ElMessage.error('创建测试目标失败，请检查控制台日志');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchGoals()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  margin-bottom: 10px;
}

.el-tabs {
  margin-top: 20px;
}

.goals-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.goal-card {
  transition: all 0.3s;
}

.goal-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.goal-card.warning {
  border: 1px solid #e6a23c;
}

.goal-card.completed-goal {
  border: 1px solid #67c23a;
}

.goal-card.failed-goal {
  border: 1px solid #f56c6c;
}

.goal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-container {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.goal-type-tag {
  margin-right: 10px;
  flex-shrink: 0;
}

.goal-title {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goal-actions {
  display: flex;
  gap: 5px;
}

.goal-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goal-info {
  flex: 1;
}

.info-row {
  margin-bottom: 10px;
  display: flex;
}

.info-row .label {
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.info-row .value {
  flex: 1;
}

.text-danger {
  color: #f56c6c;
}

.goal-progress {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.progress-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}

.progress-dialog-content h3 {
  margin-top: 0;
}

@media (max-width: 768px) {
  .goals-container {
    grid-template-columns: 1fr;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .progress-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .progress-actions .el-button {
    width: 100%;
  }
}
</style> 